package com.dataporter.gather.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 采集器的服务端
 * 
 * @author ggeagle
 *
 */
public class GatherServer implements Runnable {
	/**
	 * 日志记录器
	 */
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private TemperatureService temperatureService;
	/**
	 * 服务器端程序
	 */
	private ServerSocket serverSocket;

	public TemperatureService getTemperatureService() {
		return temperatureService;
	}

	public void setTemperatureService(TemperatureService temperatureService) {
		this.temperatureService = temperatureService;
	}

	private ExecutorService executorService;// 线程池
	private final int POOL_SIZE = 5000;// 单个CPU线程池大小

	public GatherServer(int port) throws IOException {
		this.serverSocket = new ServerSocket(port);
		// Runtime的availableProcessor()方法返回当前系统的CPU数目.
		executorService = Executors.newFixedThreadPool(Runtime.getRuntime()
				.availableProcessors() * POOL_SIZE);
		logger.info("服务器启动");
	}

	@Override
	public void run() {
		while (true) {
			Socket socket = null;
			try {
				// 接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
				socket = serverSocket.accept();
				executorService.execute(new DataGather(socket,
						this.temperatureService));
			} catch (Exception e) {
				logger.error("接收客户端连接时，发生异常！", e);
			}
		}
	}
}
